import 'package:dio/dio.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluttertoast/fluttertoast.dart';

class HttpUtil {
  static HttpUtil instance;
  Dio dio;
  BaseOptions options;

  CancelToken cancelToken = new CancelToken();

  static HttpUtil getInstance() {
    if (null == instance) {
      instance = new HttpUtil();
    }
    return instance;
  }

  HttpUtil() {
    options = new BaseOptions(
        baseUrl: "https://esi.evepc.163.com",
        //超时时间 单位毫秒
        connectTimeout: 10000,
        //响应流上前后两次接受到数据的间隔，单位为毫秒。
        receiveTimeout: 5000,
        //Http请求头.
        headers: {
          //do something
        });
    dio = new Dio(options);
  }

  // get请求
  get(url,
      {data,
      options,
      cancelToken,
      showLoading = true,
      Function success,
      Function error}) async {
    if (showLoading) {
      EasyLoading.show(status: "加载中...");
    }
    Response response;
    try {
      response = await dio.get(url,
          queryParameters: data, options: options, cancelToken: cancelToken);
      if (success != null) {
        success(response.data);
      }
    } on DioError catch (e) {
      formatError(e);
      if (error != null) {
        error(e);
      }
    }
    EasyLoading.dismiss();
  }

  // post 请求
  post(url,
      {data,
      options,
      cancelToken,
      showLoading = true,
      Function success,
      Function error}) async {
    if (showLoading) {
      EasyLoading.show(status: "加载中...");
    }
    Response response;
    try {
      response = await dio.post(url,
          queryParameters: data, options: options, cancelToken: cancelToken);
      if (success != null) {
        success(response.data);
      }
    } on DioError catch (e) {
      formatError(e);
      if (error != null) {
        error(e);
      }
    }
    EasyLoading.dismiss();
  }

  // error统一处理
  void formatError(DioError e) {
    var msg;
    if (e.type == DioErrorType.CONNECT_TIMEOUT) {
      // It occurs when url is opened timeout.
      msg = "连接超时";
    } else if (e.type == DioErrorType.SEND_TIMEOUT) {
      // It occurs when url is sent timeout.
      msg = "请求超时";
    } else if (e.type == DioErrorType.RECEIVE_TIMEOUT) {
      //It occurs when receiving timeout
      msg = "响应超时";
    } else if (e.type == DioErrorType.RESPONSE) {
      // When the server response, but with a incorrect status, such as 404, 503...
      msg = "出现异常";
    } else if (e.type == DioErrorType.CANCEL) {
      // When the request is cancelled, dio will throw a error with this type.
      msg = "请求取消";
    } else {
      //DEFAULT Default error type, Some other Error. In this case, you can read the DioError.error if it is not null.
      msg = "未知错误";
    }
    Fluttertoast.showToast(
        msg: msg,
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 1);
  }
}
